package playtools.actions;

import java.io.File;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import playtools.core.PlayOperator;
import playtools.util.LogConsole;

public class ResolveAction implements IObjectActionDelegate {
    
    private IResource resource;
    
    public ResolveAction() {
    }
    
    public void run(IAction action) {
        if (this.resource == null)
            return;
        final IProject project = resource.getProject();
        if (project == null)
            return;
        
        final File file = project.getLocation().makeAbsolute().toFile();
        LogConsole.getInstance().clearConsole();
        WorkspaceJob job = new WorkspaceJob("resolving dependencies...") {
            public IStatus runInWorkspace(IProgressMonitor monitor)
                    throws CoreException {
                monitor.beginTask("resolve project dependencies...", 3);
                
                monitor.setTaskName("执行play dependencies");
                PlayOperator.INSTANCE.execute("deps", file.getAbsolutePath());
                monitor.worked(1);
                
                monitor.setTaskName("执行play eclipsify");
                PlayOperator.INSTANCE.execute("eclipsify", file.getAbsolutePath());
                monitor.worked(1);
                
                monitor.setTaskName("正在刷新...");
                project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
                monitor.worked(1);
                
                monitor.done();
                return Status.OK_STATUS;
            }
        };
        
        job.setRule(project);
        job.schedule();
    }
    
    public void selectionChanged(IAction action, ISelection selection) {
        if (selection instanceof IStructuredSelection) {
            Object obj = ((IStructuredSelection)selection).getFirstElement();
            if (obj != null && obj instanceof IResource) {
                resource = (IResource)obj;
            }
        }
    }
    
    public void setActivePart(IAction action, IWorkbenchPart targetPart) {
    }
    
}
